import { ApiException } from "@src/services/v1_client";
import Swal from "sweetalert2";
import { HttpValidationProblemDetailsErrorsView } from "@src/components/HttpValidationProblemDetailsErrorsView";
import { withSolidContent } from "sweetalert2-solid-content";
import { FetchException } from "./useHelper";
import exp from "constants";
import { error } from "console";
import { JSXElement } from "solid-js";
import { HttpValidationProblemDetails, ProblemDetails } from "./ProblemDetails";

export const handleApiException = (exception: ApiException) => {
  return Swal.fire({
    title: "发生意料之外的错误",
    icon: "error",
    text: exception.message,
  });
};

export const handleHttpValidationProblemDetails = (
  details: IHttpValidationProblemDetails
) => {
  return withSolidContent(Swal).fire({
    title: details.title,
    icon: "warning",
    html: (
      <HttpValidationProblemDetailsErrorsView
        errors={details.errors}
      ></HttpValidationProblemDetailsErrorsView>
    ),
  });
};

export const handleProblemDetails = (details: IProblemDetails) => {
  if (Object.keys(details).includes("errors")) {
    return handleHttpValidationProblemDetails(details);
  }

  return withSolidContent(Swal).fire({
    title: details.title,
    icon: "warning",
    text: details.detail,
  });
};

export const handleFetchException = (ex: FetchException) => {
  return withSolidContent(Swal).fire({
    title: "网络错误",
    icon: "error",
    text: ex.message,
  });
};

export const handleError = (error: ApiException | IProblemDetails) => {
  if (FetchException.isFetchException(error)) {
    return handleFetchException(error);
  }

  if (ApiException.isApiException(error)) {
    return handleApiException(error);
  }

  return handleProblemDetails(error);
};

export const alertError = handleError;

export type RequestFailedLevel = "error" | "warning" | "info";

export class RequestFailedInfo {
  constructor(lv: RequestFailedLevel, title?: string, message?: JSXElement) {
    (this.level = lv), (this.title = title), (this.message = message);
  }

  level: RequestFailedLevel;
  title?: string;
  message?: JSXElement;
}

export const wrapError = (error: any) => {
  if (FetchException.isFetchException(error)) {
    return new RequestFailedInfo("error", "Fetch Failed", error.message);
  }

  if (ApiException.isApiException(error)) {
    return new RequestFailedInfo("warning", "API Exception", error.message);
  }

  if (HttpValidationProblemDetails.isHttpValidationProblemDetails(error)) {
    return new RequestFailedInfo(
      "info",
      error.title,
      (
        <HttpValidationProblemDetailsErrorsView
          errors={error.errors}
        ></HttpValidationProblemDetailsErrorsView>
      )
    );
  }

  if (ProblemDetails.isProblemDetails(error)) {
    return new RequestFailedInfo("warning", error.title, error.detail);
  }

  return new RequestFailedInfo('error', error.message);
};
